// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use
import 'package:flutter/foundation.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:mybase/base/tool/extension/FFListExt.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

/**
 * 程序启动就得调用这个类
 */
class FFSqlManager {
  // 单例公开访问点
  factory FFSqlManager() => _sharedInstance();

  // 静态、同步、私有访问点
  static FFSqlManager _sharedInstance() {
    return _instance;
  }

  // 静态私有成员，没有初始化
  static final FFSqlManager _instance = FFSqlManager._();

  // 私有构造函数
  FFSqlManager._() {}

  String dbName = "mybase.db";
  Database? db;

  List<String>? sqls;

  initSqls(List<String> sqls) {
    this.sqls = sqls;
  }

  /**
   * 打开DB
   */
  Future<void> open() async {
    String databasePath = await getDatabasesPath();
    String path = join(databasePath, dbName);

    if (db != null) {
      return;
    }

    try {
      db = await openDatabase(path);
      if (kDebugMode) {
        print('DB path >> $path');
      }

      await create();
    } catch (e) {
      if (kDebugMode) {
        print('DB open error >> $e');
      }
    }
  }

  /**
   * 创建表
   */
  Future<void> create() async {
    if (FFEmpty.listIsEmpty(sqls)) return;

    await db?.transaction((txn) async {
      for (int i = 0; i < sqls.toLength; i++) {
        await txn.execute(sqls![i]);
      }
    });
  }

// 模型调用addColumn新增字段
}
